package cn.mavor.day0929.bufferedReader;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

public class CountLinesByByte {
    public static int countLines(String filePath) throws IOException {
        try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
            byte[] buffer = new byte[1024 * 8]; // 8KB buffer
            int bytesRead;
            int lines = 0;
            boolean lastWasCR = false; // Handle CRLF as one line ending

            while ((bytesRead = inputStream.read(buffer)) != -1) {
                for (int i = 0; i < bytesRead; i++) {
                    if (buffer[i] == '\n') {
                        lines++;
                        lastWasCR = false;
                    } else if (buffer[i] == '\r') {
                        lines++;
                        lastWasCR = true;
                    } else if (lastWasCR) {
                        lastWasCR = false;
                    }
                }
            }

            return lines;
        }
    }

}